import {defineStore} from "pinia"
import { useServerStore } from './server'
interface UserInfo {
    token: string;
    username: string;
    email: string;
    password?: string;
}

interface SettingItem {
    name: string;
    normal_high: number;
    normal_low: number;
    current_val: number;
}

//@ts-ignore
let userInfo: UserInfo | null = JSON.parse(window.localStorage.getItem("userInfo")) || null
let isLogin: boolean = userInfo? true:false

export const userStore = defineStore("user",{
    state() {
        return {
            reciveMode: true,
            setting: [] as SettingItem[][], // 明确类型
            initNum: 0,
            total: 0,
            linkCode: "", // 连接码
            currentDate: '', // 当前时间
            isWatch: false, // 是否开启了数据监听
            isLogin, //用户是否登录
            userInfo, // 用户的信息
            deviceList: [], // 设备列表
            websocket: null, // websocket的对象
            isTimer: 0, // 判断定时器是否已经开启了
            localWebsocket: null as WebSocket | null,  // 本地websocket
            indexDbNum: 0,
            errList: [],
            debug: false
        }
    },
    actions: {
        // 初始化 WebSocket 连接
        initWebSocket() {
            if (this.localWebsocket) {
                this.localWebsocket.close()
            }
            
            // 使用动态端口配置
            const serverStore = useServerStore()
            const wsUrl = serverStore.getApiBaseUrl('websocket')
            console.log('user.ts连接WebSocket:', `ws://${wsUrl}`);
            this.localWebsocket = new WebSocket(`ws://${wsUrl}`)
            
            this.localWebsocket.onopen = () => {
                console.log('WebSocket 连接已建立')
            }
            
            this.localWebsocket.onerror = (error) => {
                console.error('WebSocket 错误:', error)
            }
            
            this.localWebsocket.onclose = () => {
                console.log('WebSocket 连接已关闭')
                // 尝试重新连接
                setTimeout(() => {
                    this.initWebSocket()
                }, 3000)
            }
        },
        updateIndexDbNum(count: number) {
            this.indexDbNum = count
        },
        // 关闭 WebSocket 连接
        closeWebSocket() {
            if (this.localWebsocket) {
                this.localWebsocket.close()
                this.localWebsocket = null
            }
        },
        // 修改阈值
        changeValue(option:any) {
            let index = option.id
            // 添加类型检查以安全访问
            if (this.setting[option.module_id - 1] && this.setting[option.module_id - 1][index]) {
                this.setting[option.module_id - 1][index].current_val = option.currentValue
            }
        },
        // 计算需要导入的数据量
        computeNum(num:number) {
            this.total = num
        },
        // 初始化用户的信息
        initUser(userInfo:any) {
            this.userInfo = userInfo
            this.isLogin = true
            localStorage.setItem("userInfo",JSON.stringify(userInfo))
            localStorage.setItem("isLogin",JSON.stringify(this.isLogin))
        },
        // 退出用户的登录
        exitUser() {
            this.isLogin = false
            this.userInfo = null
            localStorage.removeItem("userInfo")
            localStorage.removeItem("isLogin")
        },
         // 重置用户的密码
         resetPassword(password:string) {
            if (this.userInfo) { // 安全访问
                this.userInfo.password = password
                localStorage.setItem("userInfo",JSON.stringify(this.userInfo))
            }
        },
        // 重置系统的用户名
        resetUsername(username:string,newToken:string) {
            if (this.userInfo) { // 安全访问
                this.userInfo.username = username 
                this.userInfo.token = newToken 
                localStorage.setItem("userInfo",JSON.stringify(this.userInfo))
            }
        },
        // 绑定用户邮箱方便用户找回密码
        bindEmail(email:string) {
            if (this.userInfo) { // 安全访问
                this.userInfo.email = email
                localStorage.setItem("userInfo",JSON.stringify(this.userInfo))
            }
        },
        resetEmail() {
            if (this.userInfo) { // 安全访问
                this.userInfo.email = ""
                localStorage.setItem("userInfo",JSON.stringify(this.userInfo))
            }
        }
    },
    getters: {
        getCurrentDate():string {
            return this.currentDate
        }
    }
})